//
//  PersonalViewController.m
//  CityFire
//
//  Created by Liuyz on 2017/7/31.
//  Copyright © 2017年 刘养柱. All rights reserved.
//

#import "PersonalViewController.h"
#import "SysetmManagerViewController.h"
#import "ChangePsdViewController.h"
#import "FavoriteManagerViewController.h"
#import "MessageNotiftViewController.h"
#import "PersonInfoViewController.h"
#import "WisPersonalViewController.h"
#import "UserInfoViewModel.h"
#import "DeviceViewModel.h"
#import "NSUserDefaults+Tools.h"
#import <BlocksKit/BlocksKit+UIKit.h>

@interface PersonalViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, weak) IBOutlet UITableView *personalTableView;
@property (weak, nonatomic) IBOutlet UIImageView *avatarImageView;
@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *regionLabel;
@property (weak, nonatomic) IBOutlet UILabel *addressLabel;
@property (weak, nonatomic) IBOutlet UILabel *chargeLabel;
@property (weak, nonatomic) IBOutlet UILabel *deviceCountLabel;
@property (weak, nonatomic) IBOutlet UILabel *detectorLabel;
@property (weak, nonatomic) IBOutlet UILabel *bussinesLabel;
@property (weak, nonatomic) IBOutlet UIButton *logoutBut;
@property (nonatomic, strong) UserInfoViewModel *userInfoViewModel;
@property (nonatomic, strong) DeviceViewModel *deviceViewModel;
@property (nonatomic, strong) UserInfoModel *userInfoModel;
@property (nonatomic, strong) NSArray *PersonalInfoArray;

@end

@implementation PersonalViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.userInfoViewModel getUserInfo:nil];
    [self.deviceViewModel getPersonDeviceCount:nil];
    
    self.userInfoModel = [NSKeyedUnarchiver unarchiveObjectWithData:[NSUserDefaults readUserDataWithKey:kNSUSERDEFAULT_KEY_USERINFO]];

    if ([self.userInfoModel.role isEqualToString:@"[系统管理员]"])
    {
        self.PersonalInfoArray = @[@[@"system_icon", @"系统管理", @"设备管理及人员管理"], @[@"person_icon", @"个人信息", @"修改您的个人信息"], @[@"favioute_icon", @"偏好设置", @"设置您的偏好"], @[@"message_icon", @"消息接收", @"设置新消息提醒"], @[@"changepsd_icon", @"修改密码", @"修改您的登录密码"], @[@"phone_icon", @"服务热线", @"拨打400客服热线"], @[@"version_icon", @"版本更新", @"当前版本：1.0"]];
    } else {
        self.PersonalInfoArray = @[@[@"person_icon", @"个人信息", @"修改您的个人信息"], @[@"favioute_icon", @"偏好设置", @"设置您的偏好"], @[@"message_icon", @"消息接收", @"设置新消息提醒"], @[@"changepsd_icon", @"修改密码", @"修改您的登录密码"], @[@"phone_icon", @"服务热线", @"拨打400客服热线"], @[@"version_icon", @"版本更新", @"当前版本：1.0"]];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self.personalTableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = kPersonal_TITLE;
    self.refreshScrollView = self.personalTableView;
    //3.设置cell底线顶头
    if ([self.personalTableView respondsToSelector:@selector(setSeparatorInset:)])
    {
        [self.personalTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.personalTableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [self.personalTableView setLayoutMargins:UIEdgeInsetsZero];
    }
    self.isAutoRefresh = YES;
    self.userInfoModel = [NSKeyedUnarchiver unarchiveObjectWithData:[NSUserDefaults readUserDataWithKey:kNSUSERDEFAULT_KEY_USERINFO]];
    
    [self bindRAC];
    [self configHeaderInfo];
//    self.PersonalInfoArray = [NSArray array];
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:kNOTIFICATION_UPDATEUSERCENTER object:nil] takeUntil:[self rac_willDeallocSignal]] subscribeNext: ^(NSNotification *notification) {
        NSLog(@"我要更新数据了");
        [self endRefresh];
        UserInfoModel *usermodel = [notification object];
        if ([usermodel.role isEqualToString:@"[系统管理员]"]) {
            self.PersonalInfoArray = @[@[@"system_icon", @"系统管理", @"设备管理及人员管理"], @[@"person_icon", @"个人信息", @"修改您的个人信息"], @[@"favioute_icon", @"偏好设置", @"设置您的偏好"], @[@"message_icon", @"消息接收", @"设置新消息提醒"], @[@"changepsd_icon", @"修改密码", @"修改您的登录密码"], @[@"phone_icon", @"服务热线", @"拨打400客服热线"]];
            //, @[@"version_icon", @"版本更新", @"当前版本：1.0"]
        } else {
            self.PersonalInfoArray = @[@[@"person_icon", @"个人信息", @"修改您的个人信息"], @[@"favioute_icon", @"偏好设置", @"设置您的偏好"], @[@"message_icon", @"消息接收", @"设置新消息提醒"], @[@"changepsd_icon", @"修改密码", @"修改您的登录密码"], @[@"phone_icon", @"服务热线", @"拨打400客服热线"]];
            ///, @[@"version_icon", @"版本更新", @"当前版本：1.0"]
        }
        [self.personalTableView reloadData];
    }];
    //下拉刷新配制
    self.refreshActionBlock = ^{
        NSLog(@"下拉刷新配制 block");
        [self.deviceViewModel getPersonDeviceCount:nil];
        [self endRefresh];
    };
}

-(void) viewDidLayoutSubviews{
    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:16]};
    CGSize size = [self.regionLabel.text boundingRectWithSize:CGSizeMake(360, MAXFLOAT) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    
    CGRect newUserNameFrame=self.regionLabel.frame;
    NSInteger newWidth =size.width+10;
    newUserNameFrame.size.width=newWidth;
    self.regionLabel.frame=newUserNameFrame;
    self.regionLabel.backgroundColor = [UIColor whiteColor];
}
#pragma mark - 设置header信息
- (void)configHeaderInfo {
    self.regionLabel.text = NSSTRING(@"所属辖区", self.userInfoModel.ssxq);
    
    
    
    
    self.userNameLabel.text = NSSTRING(@"用户名", self.userInfoModel.chnUserName);
    self.addressLabel.text = NSSTRING(@"用户地址", self.userInfoModel.address);
    self.chargeLabel.text = NSSTRING(@"防火负责人",  self.userInfoModel.fhzrr);
    
    self.logoutBut.layer.cornerRadius = self.logoutBut.frame.size.height / 2-2;
    self.logoutBut.layer.masksToBounds = YES;
    self.bussinesLabel.layer.cornerRadius = 2.0f;
    self.bussinesLabel.layer.masksToBounds = YES;
}

- (void)bindRAC {
    @weakify(self);
    [RACObserve(self.userInfoViewModel, userInfoModel) subscribeNext:^(UserInfoModel  *userinfoModel) {
        @strongify(self);
        self.regionLabel.text = NSSTRING(@"所属辖区", self.userInfoModel.ssxq);
        self.userNameLabel.text = NSSTRING(@"用户名", self.userInfoModel.chnUserName);
        self.addressLabel.text = NSSTRING(@"用户地址", self.userInfoModel.address);
        self.chargeLabel.text = NSSTRING(@"防火负责人",  self.userInfoModel.fhzrr);
    }];
    
    [RACObserve(self.deviceViewModel, devicesModel) subscribeNext:^(DevicesModel *devicesModel) {
        @strongify(self);
        self.deviceCountLabel.text = NSSTRING_LONG(@"设备数量",(long)devicesModel.devicenum);
        self.detectorLabel.text = NSSTRING_LONG(@"探测器数量",(long)devicesModel.detectorAmount);
    }];
}

#pragma mark - tableViewDelegate
-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    header.contentView.backgroundColor = RGB(238, 233, 233);
}
-(void)tableView:(UITableView *)tableView willDisplayFooterView:(nonnull UIView *)view forSection:(NSInteger)section
{
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    header.contentView.backgroundColor = RGB(238, 233, 233);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
{
    return 1.0f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1.0f;
}
/**
 *  设置cell底线顶头
 */
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.PersonalInfoArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PersonalCell"];
    if(cell != nil)
    {
        cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"PersonalCell"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    cell.textLabel.text = self.PersonalInfoArray[indexPath.row][1];
    cell.detailTextLabel.text = self.PersonalInfoArray[indexPath.row][2];
    cell.detailTextLabel.textColor = [UIColor lightGrayColor];
    cell.imageView.image = [UIImage imageNamed:self.PersonalInfoArray[indexPath.row][0]];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if ([self.userInfoModel.role isEqualToString:@"[系统管理员]"]) {
        switch (indexPath.row) {
            case 0:
            {
                SysetmManagerViewController *sysMVC = kVCFromSB(kPersonalStoryBoard, SysetmManagerViewController);
                sysMVC.aURL = [NSString stringWithFormat:@"%@?sessionid=%@&username=%@", kBASE_URL, self.userInfoModel.seeeionID, self.userInfoModel.engUserName];
                sysMVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:sysMVC animated:YES];
            }
                break;
            case 1:
            {
//                PersonInfoViewController *infoVC = kVCFromSB(kPersonalStoryBoard, PersonInfoViewController);
                WisPersonalViewController *infoVC = [[WisPersonalViewController alloc]init];
                infoVC.personInfoModel = self.userInfoModel;
                infoVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:infoVC animated:YES];
            }
                break;
            case 2:
            {
                FavoriteManagerViewController *favoriteVC = kVCFromSB(kPersonalStoryBoard, FavoriteManagerViewController);
                favoriteVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:favoriteVC animated:YES];
            }
                break;
            case 3:
            {
                MessageNotiftViewController *notiVC = kVCFromSB(kPersonalStoryBoard, MessageNotiftViewController);
                notiVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:notiVC animated:YES];
            }
                break;
            case 4:
            {
                ChangePsdViewController *changePsdVC = kVCFromSB(kPersonalStoryBoard, ChangePsdViewController);
                changePsdVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:changePsdVC animated:YES];
            }
                break;
            case 5:
            {
                [self callServiewHotLine];
            }
                break;
            case 6:
            {
                //版本更新
            }
                break;
            default:
                break;
        }
    } else {
        switch (indexPath.row) {
            case 0:
            {
//                PersonInfoViewController *infoVC = kVCFromSB(kPersonalStoryBoard, PersonInfoViewController);
                WisPersonalViewController *infoVC = [[WisPersonalViewController alloc]init];
                infoVC.personInfoModel = self.userInfoModel;
                infoVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:infoVC animated:YES];
            }
                break;
            case 1:
            {
                FavoriteManagerViewController *favoriteVC = kVCFromSB(kPersonalStoryBoard, FavoriteManagerViewController);
                favoriteVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:favoriteVC animated:YES];
            }
                break;
            case 2:
            {
                MessageNotiftViewController *notiVC = kVCFromSB(kPersonalStoryBoard, MessageNotiftViewController);
                notiVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:notiVC animated:YES];
            }
                break;
            case 3:
            {
                ChangePsdViewController *changePsdVC = kVCFromSB(kPersonalStoryBoard, ChangePsdViewController);
                changePsdVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:changePsdVC animated:YES];
            }
                break;
            case 4:
            {
                [self callServiewHotLine];
            }
                break;
            case 5:
            {
                //版本更新
            }
                break;
            default:
                break;
        }
    }
}

#pragma mark - others
//拨打客服热线
- (void)callServiewHotLine
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"服务热线" message:@"是否拨打022-24165036电话进行咨询" preferredStyle: UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel:022-24165036"]];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - setter and getter
- (IBAction)logOut:(id)sender
{
    [self.userInfoViewModel userLogOut:nil];
}

- (UserInfoViewModel *)userInfoViewModel
{
    if (_userInfoViewModel == nil) {
        _userInfoViewModel = [[UserInfoViewModel alloc] init];
    }
    return _userInfoViewModel;
}

- (UserInfoModel *)userInfoModel
{
    if (_userInfoModel == nil) {
        _userInfoModel = [[UserInfoModel alloc] init];
    }
    return _userInfoModel;
}

- (DeviceViewModel *)deviceViewModel
{
    if (_deviceViewModel == nil) {
        _deviceViewModel = [[DeviceViewModel alloc] init];
    }
    return _deviceViewModel;
}

- (NSArray *)PersonalInfoArray
{
    if (_PersonalInfoArray == nil) {
        _PersonalInfoArray = [NSArray array];
    }
    
    return _PersonalInfoArray;
}

- (void)dealloc
{
    [[NSNotificationCenter  defaultCenter] removeObserver:self  name:kNOTIFICATION_UPDATEUSERCENTER object:nil];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end

